<template>
  <div class="home-container" ref="home-container">
    <ElectronWindowsControlButtonView
      v-if="sharedMiscState.isElectronWindowsOrLinux"
    />

    <div class="home">
      <section class="menu-container bd-right">
        <div>
          <!-- <tippy
            to="#infoTrigger"
            interactive
            :animate-fill="false"
            distant="7"
            theme="light"
            animation="fade"
            trigger="click"
            :arrow="true"
          >
            <template #content>
              <UserCardView
                v-if="sharedContactState.selfUserInfo"
                v-on:close="closeUserCard"
                :enable-update-portrait="true"
                :user-info="sharedContactState.selfUserInfo"
              />
            </template>
          </tippy> -->

          <!-- 头像 -->
          <!-- <BaseImage
            ref="userCardTippy"
            id="infoTrigger"
            class="kang-avatar radius mt-10"
            draggable="false"
            @click.prevent="onClickPortrait"
            :src="sharedContactState.selfUserInfo.portrait"
            v-if="sharedContactState.selfUserInfo"
          ></BaseImage> -->

          <!-- 头像 -->
          <BaseImage
            class="kang-avatar radius mt-10"
            :src="sharedContactState.selfUserInfo.portrait"
            @click.prevent="onClickPortrait"
            v-if="sharedContactState.selfUserInfo"
          ></BaseImage>
        </div>
        <nav class="menu">
          <ul>
            <!-- 聊天 -->
            <li class="hover click" @click="go2Conversation">
              <div
                class="menu-item"
                :class="
                  this.$router.currentRoute.value.path === '/home'
                    ? 'active'
                    : ''
                "
              >
                <img
                  class="icon active"
                  src="@/kang/img/icon_chat_active.png"
                />
                <img class="icon" src="@/kang/img/icon_chat.png" />
                <div class="label">聊天</div>
                <em
                  class="red-dot"
                  style="top: 0; right: -5px"
                  v-show="unread > 0"
                >
                  {{ unread > 99 ? '···' : unread }}
                </em>
              </div>
            </li>

            <!-- 好友 -->
            <li class="hover click" @click="go2Contact">
              <div
                class="menu-item"
                :class="
                  this.$router.currentRoute.value.path === '/home/contact'
                    ? 'active'
                    : ''
                "
              >
                <img
                  class="icon active"
                  src="@/kang/img/icon_friend_active.png"
                />
                <img class="icon" src="@/kang/img/icon_friend.png" />
                <div class="label">好友</div>
                <em
                  class="red-dot"
                  style="top: 0; right: -5px"
                  v-show="sharedContactState.unreadFriendRequestCount > 0"
                >
                  {{
                    sharedContactState.unreadFriendRequestCount > 99
                      ? '99'
                      : sharedContactState.unreadFriendRequestCount
                  }}
                </em>
              </div>
            </li>

            <!-- 群聊 -->
            <li class="hover click" @click="go2Group">
              <div
                class="menu-item"
                :class="
                  this.$router.currentRoute.value.path === '/home/group'
                    ? 'active'
                    : ''
                "
              >
                <img
                  class="icon active"
                  src="@/kang/img/icon_group_active.png"
                />
                <img class="icon" src="@/kang/img/icon_group.png" />
                <div class="label">群聊</div>
              </div>
            </li>

            <!-- 邀请码 -->
            <li class="hover click" @click="dialogInvite">
              <div class="menu-item">
                <img class="icon" src="@/kang/img/icon_invite_code.png" />
                <div class="label">邀请码</div>
              </div>
            </li>

            <!-- 设置 -->
            <li class="hover click" @click="dialogSetting">
              <div class="menu-item">
                <img class="icon" src="@/kang/img/icon_setting.png" />
              </div>
            </li>
          </ul>
        </nav>
      </section>
      <router-view v-slot="{ Component, route }">
        <keep-alive v-show="route.path !== '/home/ai'">
          <component :is="Component" :key="route.path" />
        </keep-alive>
        <AI v-show="route.path === '/home/ai'" />
      </router-view>
      <div v-if="sharedMiscState.connectionStatus === -1" class="unconnected">
        网络连接断开
      </div>
      <div class="drag-area" :style="dragAreaLeft"></div>
      <UseDraggable
        v-if="!sharedMiscState.isElectron && sharedMiscState.isVoipOngoing"
        class="voip-div-container"
        draggable="true"
        :initial-value="{ x: '50%', y: '50%' }"
        :prevent-default="true"
        v-bind:class="{
          single: voipProxy.type === 'single',
          multi: voipProxy.type === 'multi',
          conference: voipProxy.type === 'conference',
        }"
      >
        <Single v-if="voipProxy.type === 'single'" ref="handle-id" />
        <Multi v-if="voipProxy.type === 'multi'" ref="handle-id" />
        <Conference v-if="voipProxy.type === 'conference'" ref="handle-id" />
      </UseDraggable>
    </div>

    <!-- 邀请码弹窗 -->
    <n-modal
      class="kang-modal"
      style="background-color: var(--color-bg)"
      preset="dialog"
      title="邀请码"
      :close-on-esc="true"
      v-model:show="dialogInviteVisible"
    >
      <InviteComp></InviteComp>
    </n-modal>

    <!-- 设置弹窗 -->
    <n-modal
      class="kang-modal"
      preset="dialog"
      title="设置"
      :close-on-esc="true"
      v-model:show="dialogSettingVisible"
    >
      <SettingComp></SettingComp>
    </n-modal>

    <!-- 我的收藏弹窗 -->
    <n-modal
      style="width: 550px"
      class="kang-modal"
      preset="dialog"
      title="收藏"
      :close-on-esc="true"
      v-model:show="collectInfoConfig.visible"
    >
      <CollectComp :config="collectInfoConfig"></CollectComp>
    </n-modal>

    <!-- 添加好友弹窗 -->
    <n-modal
      class="kang-modal"
      preset="dialog"
      title="添加好友"
      :close-on-esc="true"
      v-model:show="dialogAddFriendVisible"
    >
      <AddFriendComp></AddFriendComp>
    </n-modal>

    <!-- 选择用户全局组件 -->
    <n-modal
      class="kang-modal"
      preset="dialog"
      :title="selectUserConfig.title || '选择用户'"
      :close-on-esc="true"
      v-model:show="selectUserConfig.visible"
    >
      <SelectUser :config="selectUserConfig"></SelectUser>
    </n-modal>

    <!-- 群管理 -->
    <n-modal
      class="kang-modal"
      style="width: 400px"
      preset="dialog"
      title="群管理"
      :close-on-esc="true"
      v-model:show="dialogGroupManagerVisible"
    >
      <GroupManager></GroupManager>
    </n-modal>

    <!-- 个人信息面板 -->
    <n-modal
      class="kang-modal"
      style="width: 400px"
      preset="dialog"
      title="个人信息"
      :close-on-esc="true"
      v-model:show="userInfoConfig.visible"
    >
      <UserInfoComp
        :config="userInfoConfig"
        :info="shareConversationState.currentConversationInfo"
      ></UserInfoComp>
    </n-modal>

    <!--  积分余额面板 -->
    <n-modal
      class="kang-modal"
      style="width: 350px"
      preset="dialog"
      title="积分余额"
      :close-on-esc="true"
      v-model:show="dialogUserScoreVisible"
    >
      <UserScoreComp
        :config="userInfoConfig"
        :info="shareConversationState.currentConversationInfo"
      ></UserScoreComp>
    </n-modal>
  </div>
</template>

<script>
import UserCardView from './user/UserCardView.vue'
import store from '../../store'
import wfc from '../../wfc/client/wfc'
import EventType from '../../wfc/client/wfcEvent'
import ConnectionStatus from '../../wfc/client/connectionStatus'
import ElectronWindowsControlButtonView from '../common/ElectronWindowsControlButtonView.vue'
import { removeItem } from '../util/storageHelper'
import { ipcRenderer } from '../../platform'
import avenginekit from '../../wfc/av/internal/engine.min'
import avenginekitproxy from '../../wfc/av/engine/avenginekitproxy'
import IpcEventType from '../../ipcEventType'
import { isElectron } from '../../platform'
import Single from '../voip/Single.vue'
import Multi from '../voip/Multi.vue'
import Conference from '../voip/conference/Conference.vue'
import 'tippy.js/dist/tippy.css' // optional for styling
import { UseDraggable } from '@vueuse/components'
import AI from './AI.vue'
import Config from '../../config'
import mitt from '@/kang/js/mitt'

import InviteComp from '@/kang/components/InviteComp.vue'
import SettingComp from '@/kang/components/SettingComp.vue'
import CollectComp from '@/kang/components/CollectComp.vue'
import AddFriendComp from '@/kang/components/AddFriendComp.vue'
import GroupManager from '@/kang/components/group/GroupManager.vue'
import UserInfoComp from '@/kang/components/user/UserInfo.vue'
import UserScoreComp from '@/kang/components/user/UserScore.vue'

var avenginkitSetuped = false
export default {
  data() {
    return {
      sharedContactState: store.state.contact,
      sharedMiscState: store.state.misc,
      shareConversationState: store.state.conversation,
      supportConference: avenginekit.startConference !== undefined,
      fileWindow: null,
      voipProxy: avenginekitproxy,
      dialogInviteVisible: false,
      dialogSettingVisible: false,
      dialogAddFriendVisible: false,
      dialogGroupManagerVisible: false,
      dialogUserScoreVisible: false,

      // 选择用户
      selectUserConfig: {},

      // 个人信息
      userInfoConfig: {},

      // 我的收藏
      collectInfoConfig: {},

      mitt,
    }
  },

  methods: {
    dialogInvite(e = true) {
      this.dialogInviteVisible = e
    },
    dialogSetting(e = true) {
      this.dialogSettingVisible = e
    },
    dialogCollect(e) {
      this.collectInfoConfig.type = e.type
      this.collectInfoConfig.visible = e.visible
    },
    dialogAddFriend(e = true) {
      this.dialogAddFriendVisible = e
    },
    dialogSelectUser(e) {
      this.selectUserConfig = e
    },
    dialogGroupManager(e = true) {
      this.dialogGroupManagerVisible = e
    },
    dialogUserInfo(e) {
      this.userInfoConfig.userId = e.userId || ''
      this.userInfoConfig.isSelf = e.isSelf || false
      this.userInfoConfig.visible = e.visible
    },
    dialogUserScore(e = true) {
      this.dialogUserScoreVisible = e
    },
    onClickPortrait(event) {
      this.dialogUserInfo({
        userId: this.sharedContactState.selfUserInfo.uid,
        isSelf: true,
        visible: true,
      })
    },
    go2Conversation() {
      if (this.$router.currentRoute.value.path === '/home') {
        this.$eventBus.$emit('scrollToNextUnreadConversation')
        return
      }
      mitt.emit('clearKeyword')
      this.$router.replace('/home')
    },
    go2Contact() {
      if (this.$router.currentRoute.path === '/home/contact') {
        return
      }
      mitt.emit('clearKeyword')
      this.$router.replace('/home/contact')
    },
    go2Group() {
      if (this.$router.currentRoute.path === '/home/group') {
        return
      }
      mitt.emit('clearKeyword')
      this.$router.replace('/home/group')
    },
    go2Fav() {
      if (this.$router.currentRoute.path === '/home/fav') {
        return
      }
      this.$router.replace('/home/fav')
    },
    closeUserCard() {
      console.log('closeUserCard')
      this.$refs['userCardTippy']._tippy.hide()
    },
    onConnectionStatusChange(status) {
      if (
        status === ConnectionStatus.ConnectionStatusRejected ||
        status === ConnectionStatus.ConnectionStatusLogout ||
        status === ConnectionStatus.ConnectionStatusSecretKeyMismatch ||
        status === ConnectionStatus.ConnectionStatusTokenIncorrect ||
        status === ConnectionStatus.ConnectionStatusKickedOff ||
        // TODO 断网时，显示网络断开状态
        // || status === ConnectionStatus.ConnectionStatusUnconnected
        wfc.getUserId() === ''
      ) {
        if (this.$router.currentRoute.path !== '/') {
          this.$router.replace({ path: '/' })
        }
        if (
          status === ConnectionStatus.ConnectionStatusSecretKeyMismatch ||
          status === ConnectionStatus.ConnectionStatusLogout ||
          status === ConnectionStatus.ConnectionStatusTokenIncorrect ||
          status === ConnectionStatus.ConnectionStatusKickedOff ||
          status === ConnectionStatus.ConnectionStatusRejected
        ) {
          removeItem('userId')
          removeItem('token')

          avenginekitproxy.forceCloseVoipWindow()
          console.error('连接失败', ConnectionStatus.desc(status))
        }
      }
    },
  },

  computed: {
    aiPortalUrl() {
      return Config.AI_PORTAL_URL
    },
    unread() {
      let count = 0
      this.shareConversationState.conversationInfoList.forEach((info) => {
        if (info.isSilent) {
          return
        }
        let unreadCount = info.unreadCount
        count += unreadCount.unread
      })
      return count
    },
    dragAreaLeft() {
      return {
        left: 'calc(60px + 261px)',
      }
    },
  },

  created() {
    wfc.eventEmitter.on(
      EventType.ConnectionStatusChanged,
      this.onConnectionStatusChange
    )
    this.onConnectionStatusChange(wfc.getConnectionStatus())

    if (!isElectron() && !avenginkitSetuped) {
      avenginekit.setup()
      avenginkitSetuped = true
    }
  },

  mounted() {
    avenginekitproxy.onVoipCallErrorCallback = (errorCode) => {
      if (errorCode === -1) {
        this.$notify({
          title: '不能发起或接听新的音视频通话',
          text: '目前有音视频通话正在进行中',
          type: 'warn',
        })
      } else if (errorCode === -2) {
        if (isElectron()) {
          console.error(`不支持音视频通话，原因可能是:
                        1. 可通过这个网页测试浏览器对音视频通话的支持情况，https://docs.wildfirechat.cn/webrtc/abilitytest/
                        2. 确保系统已授予当前应用 摄像头 和 麦克风 权限
                    `)
        } else {
          console.error(`不支持音视频通话，原因可能是:
                        1. 浏览器上，只有通过 http://localhost 或 https://xxxx 访问的网页才支持音视频通话
                        2. 可通过这个网页测试浏览器对音视频通话的支持情况，https://docs.wildfirechat.cn/webrtc/abilitytest/
                        3. 确保浏览器已授予网页 摄像头 和 麦克风 权限
                        4. 确保系统已授予浏览器 摄像头 和麦克风 权限
                        5. 配置 https，请参考：https://docs.wildfirechat.cn/faq/web/https.html
                    `)
        }
        this.$notify({
          title: '不支持音视频通话',
          text: '请打开控制台查看具体原因',
          type: 'warn',
        })
      }
    }

    mitt.on('dialog:invite', this.dialogInvite)
    mitt.on('dialog:setting', this.dialogSetting)
    mitt.on('dialog:collect', this.dialogCollect)
    mitt.on('dialog:addGroup', this.dialogAddGroup)
    mitt.on('dialog:addFriend', this.dialogAddFriend)
    mitt.on('dialog:selectUser', this.dialogSelectUser)
    mitt.on('dialog:groupManager', this.dialogGroupManager)
    mitt.on('dialog:userInfo', this.dialogUserInfo)
    mitt.on('dialog:userScore', this.dialogUserScore)
  },
  unmounted() {
    wfc.eventEmitter.removeListener(
      EventType.ConnectionStatusChanged,
      this.onConnectionStatusChange
    )

    mitt.off('dialog:invite', this.dialogInvite)
    mitt.off('dialog:setting', this.dialogSetting)
    mitt.off('dialog:collect', this.dialogCollect)
    mitt.off('dialog:addGroup', this.dialogAddGroup)
    mitt.off('dialog:addFriend', this.dialogAddFriend)
    mitt.off('dialog:selectUser', this.dialogSelectUser)
    mitt.off('dialog:groupManager', this.dialogGroupManager)
    mitt.off('dialog:userInfo', this.dialogUserInfo)
    mitt.off('dialog:userScore', this.dialogUserScore)

    console.log('home destroy')
  },

  components: {
    AI,
    Conference,
    Multi,
    Single,
    UserCardView,
    ElectronWindowsControlButtonView,
    UseDraggable,
    InviteComp,
    SettingComp,
    CollectComp,
    AddFriendComp,
    GroupManager,
    UserInfoComp,
    UserScoreComp,
  },
  directives: {},
}
</script>

<style lang="scss" scoped>
.home {
  display: flex;
  width: calc(100vw - var(--main-margin-left) - var(--main-margin-right));
  height: calc(
    100vh - var(--main-margin-top) - var(--main-margin-bottom) - 31px
  );
  justify-content: center;
  align-items: center;
  background-color: white;
  border-radius: var(--main-border-radius);
  overflow: hidden;
}

.menu-container {
  width: 65px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: var(--color-white);
  border-top-left-radius: var(--main-border-radius);
  border-bottom-left-radius: var(--main-border-radius);
  padding: var(--home-menu-padding-top) 0 20px 0;
  // -webkit-app-region: drag;
}

.menu {
  flex: 1;
}

.menu ul {
  height: 100%;
  display: flex;
  flex-direction: column;
  // -webkit-app-region: drag;
}

.menu ul li {
  width: 45px;
  margin: 0 auto;
  text-align: center;
  font-size: 12px;
  padding: 5px 0;
  margin-top: 15px;
  line-height: 1.2;
  border-radius: var(--border-radius);

  .menu-item {
    .icon {
      width: 24px;

      &.active {
        display: none;
      }
    }

    .label {
      color: var(--color-basic);
    }

    &.active {
      .icon {
        display: none;

        &.active {
          display: inline-block;
        }
      }

      .label {
        color: var(--color-blue);
      }
    }
  }
}

.menu ul li:last-of-type {
  margin-top: auto;
}

.menu .menu-item {
  position: relative;
}

.drag-area {
  position: absolute;
  top: 0;
  height: 60px;
  right: 140px;
  z-index: -1;
  // -webkit-app-region: drag;
}

.unconnected {
  position: absolute;
  top: 0;
  left: 60px;
  right: 0;
  color: red;
  padding: 15px 0;
  text-align: center;
  background: #f2f2f280;
  /*box-shadow: 0 0 1px #000;*/
}

.voip-div-container {
  background: #292929;
  position: fixed;
  margin: auto;
  border-radius: 5px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  display: flex;
  flex-direction: column;
}

.voip-div-container.single {
  width: 360px;
  height: 640px;
}

.voip-div-container.multi {
  width: 960px;
  height: 600px;
}

.voip-div-container.conference {
  width: 960px;
  height: 600px;
}

.voip-div-container .title {
  text-align: center;
  padding: 5px 0;
  background: #b6b6b6;
  display: flex;
  justify-content: center;
  align-content: center;
}

.voip-div-container .title i {
  pointer-events: none;
}

.voip-div-container .title i:hover {
  color: #868686;
}

.voip-div-container .title i:active {
  color: #868686;
}

.voip-div-container .content {
  flex: 1;
  border: none;
}
</style>
